package com.cf.service.impl;

import com.cf.dao.RoleDao;
import com.cf.dao.UserDao;
import com.cf.entity.User;
import com.cf.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    //    登录
    @Override
    public User login(String username) {
        User user = userDao.login(username);
        return user;
    }
    //  分页查询
    @Override
    public PageInfo<User> selectUser(int pagenum, int pagesize, Map map) {
        PageHelper.startPage(pagenum,pagesize);
        List<User> users = userDao.selectUser(map);
        if(users!=null){
            for(User u:users){
                User user = userDao.selectRoleById(u.getUserid());
                u.setRoles(user.getRoles());
            }
        }
        PageInfo<User> userPageInfo =new PageInfo<>(users);
        return userPageInfo;
    }
    //注册
    @Override
    public int register(User user) {
        user.setToken(UUID.randomUUID().toString().replace("_",""));
        return userDao.register(user);
    }

    @Override
    public int uploadImg(User user) {
        return userDao.uploadImg(user);
    }

    @Override
    public int updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public int delUser(long id) {
        return userDao.delUser(id);
    }

    @Override
    public User selectUserById(long id) {
        return userDao.selectUserById(id);
    }

    @Override
    public User selectRoleById(long id) {
        User user = userDao.selectRoleById(id);
        return user;
    }

    @Override
    public int insertRole(long userid, long[] roleid) {
        userDao.delRoleById(userid);
        Map map = new HashMap();
        map.put("userid",userid);
        for (int i = 0; i < roleid.length; i++) {
            map.put("roleid",roleid[i]);
            userDao.insertRole(map);
        }
        return 1;
    }

    @Override
    public int addManager(User user) {
        user.setToken(UUID.randomUUID().toString().replace("_",""));
        return userDao.addManager(user);
    }

    @Override
    public String selectPassword(long id) {
        return userDao.selectPassword(id);
    }


}
